package com.cctv.fmaed.module.redis.memory.service.impl;

import com.cctv.fmaed.module.redis.memory.enums.CacheKeyPrefixEnum;
import com.cctv.fmaed.module.redis.memory.pojo.po.DeviceRegisterPO;
import com.cctv.fmaed.module.redis.memory.service.DeviceService;
import com.cctv.fmaed.module.redis.memory.utils.RandomUtils;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
public class DeviceServiceImpl implements DeviceService {

    private StringRedisTemplate stringRedisTemplate;

    public DeviceServiceImpl(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }


    @Override
    public void putDeviceRegister(String deviceId, String deviceName) {
        HashOperations<String, String, String> hashOps = stringRedisTemplate.opsForHash();

        // 生成GUID
        String guid = RandomUtils.getGuid();

        List<String> keys = new ArrayList<>(2);
        keys.add(CacheKeyPrefixEnum.DEVICE_ID.key(deviceId));
        keys.add(CacheKeyPrefixEnum.DEVICE_GUID.key(guid));

        // 生成SecretKey
        String secretKey = RandomUtils.getSecretKey();
        String now = String.valueOf(System.currentTimeMillis());

        Map<String, String> idEntries = new LinkedHashMap<>();
        idEntries.put(DeviceRegisterPO.HASH_KEY_DEVICE_ID, deviceId);
        idEntries.put(DeviceRegisterPO.HASH_KEY_GUID, guid);
        idEntries.put(DeviceRegisterPO.HASH_KEY_SECRET_KEY, secretKey);
        idEntries.put(DeviceRegisterPO.HASH_KEY_CREATE_TIME, now);

        hashOps.putAll(keys.get(0), idEntries);

        Map<String, String> guidEntries = new LinkedHashMap<>();
        guidEntries.put(DeviceRegisterPO.HASH_KEY_DEVICE_ID, deviceId);
        guidEntries.put(DeviceRegisterPO.HASH_KEY_GUID, guid);
        guidEntries.put(DeviceRegisterPO.HASH_KEY_SECRET_KEY, secretKey);
        guidEntries.put(DeviceRegisterPO.HASH_KEY_CREATE_TIME, now);
        guidEntries.put(DeviceRegisterPO.HASH_KEY_DEVICE_NAME, deviceName);
        guidEntries.put(DeviceRegisterPO.HASH_KEY_UPDATE_TIME, now);

        hashOps.putAll(keys.get(1), guidEntries);
    }

}
